package com.hncc.kumao.interceptor;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.hncc.kumao.util.ConstValue;
import com.hncc.kumao.util.JWTUtils;
import com.hncc.kumao.util.JedisUtils;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.MethodFilterInterceptor;

import redis.clients.jedis.Jedis;

public class CheckTokenInterceptor extends MethodFilterInterceptor {

    @Override
    protected String doIntercept(ActionInvocation invocation) throws Exception {
        //System.out.println("验证权限");
        String token = "";
        try {
            //从Request中获取数据(这个数据来自拦截器)
            String requestData = (String) ServletActionContext.getRequest().getAttribute(ConstValue.REQUEST_DATA);
            token = JSON.parseObject(requestData).getString("token");
        } catch (Exception e) {
            jsonReturn(false, ConstValue.RESULT_CODE_SERVER_ERROR, "服务器好像出了点问题");
            e.printStackTrace();
            return null;
        }
        if(token == null || token.trim().length() <= 0) {
            jsonReturn(false, ConstValue.RESULT_CODE_BAD_REQUEST, "缺少访问令牌");
            return null;
        }
        //从redis中根据token获取用户id
        String parseId = "";
        try {
            parseId = JWTUtils.parseJWT(token);
        } catch (Exception e1) {
            jsonReturn(false, ConstValue.RESULT_CODE_BAD_REQUEST, "访问令牌有误");
            e1.printStackTrace();
            return null;
        }
        
        Jedis jedis = JedisUtils.getJedis();
        String userId = jedis.hget(ConstValue.SERVER_TOKEN, parseId);
        JedisUtils.closeJedis(jedis);
        if(userId == null || userId.trim().length() <= 0 || !parseId.equals(userId)) {
            jsonReturn(false, ConstValue.RESULT_CODE_BAD_REQUEST, "访问令牌无效");
            return null;
        }
        //令牌有效，将查出来的id存入request
        ServletActionContext.getRequest().setAttribute(ConstValue.REQUEST_USER_ID, userId);
        return invocation.invoke();
    }
    
    //返回json格式数据
    public void jsonReturn(boolean success, int code, Object value) {
       Map map = new HashMap();
       map.put(ConstValue.SUCCESS, success);
       map.put(ConstValue.CODE, code);
       map.put(ConstValue.DATA, value);
       HttpServletResponse response = ServletActionContext.getResponse();
       response.setContentType("text/html;charset=UTF-8");
       response.setCharacterEncoding("UTF-8");
       try {
           String jsonString = JSON.toJSONString(map, SerializerFeature.DisableCircularReferenceDetect);
           //System.out.println(jsonString);
           response.getWriter().write(jsonString);
       } catch (IOException e) {
           e.printStackTrace();
       }
    }
}
